package com.nuanshui.heatedloan.msgcenter.service.smspush;

import com.alibaba.dubbo.config.annotation.Service;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.BatchSmsAttributes;
import com.aliyun.mns.model.MessageAttributes;
import com.aliyun.mns.model.RawTopicMessage;
import com.aliyun.mns.model.TopicMessage;
import com.nuanshui.heatedloan.msgcenter.facade.smspush.SmsPushService;
import com.nuanshui.heatedloan.msgcenter.model.SmsMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.Map;

//@Service
public class AliCloudSmsPushServiceImpl implements SmsPushService {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Value("${ali.sms.regionId}")
	private String regionId;
	@Value("${ali.sms.aliSmsAccessKeyId}")
	private String aliSmsAccessKeyId;
	@Value("${ali.sms.aliSecret}")
	private String aliSecret;
	@Value("${ali.sms.endpointName}")
	private String endpointName;
	@Value("${ali.sms.aliCloudProduct}")
	private String aliCloudProduct;
	@Value("${ali.sms.aliCloudDomain}")
	private String aliCloudDomain;
	@Value("${ali.sms.aliCloundTopicName}")
	private String aliCloundTopicName;

	public boolean sendMsg(SmsMsg msg)
	{
		return sendMsg(msg.getMobile(),msg.getTempCode(),msg.getParams(),msg.getSignName());
	}

	public boolean  sendMsg(String mobile, String tempCode, Map<String, Object> params,String signName){
		logger.info("------------------初始化发送短信参数---------------------------------------");
		/**
		 * Step 1. 获取主题引用
		 */
		CloudAccount account = new CloudAccount(aliSmsAccessKeyId, aliSecret, endpointName);
		MNSClient client = account.getMNSClient();
		CloudTopic topic = client.getTopicRef(aliCloundTopicName);

		/**
		 * Step 2. 设置SMS消息体（必须）
		 *
		 * 注：目前暂时不支持消息内容为空，需要指定消息内容，不为空即可。
		 */
		RawTopicMessage msg = new RawTopicMessage();
		msg.setMessageBody("sms-message");

		/**
		 * Step 3. 生成SMS消息属性
		 */
		MessageAttributes messageAttributes = new MessageAttributes();
		BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
		// 3.1 设置发送短信的签名（SMSSignName）
		batchSmsAttributes.setFreeSignName(signName);
		// 3.2 设置发送短信使用的模板（SMSTempateCode）
		logger.info("================"+tempCode+"======================");
		batchSmsAttributes.setTemplateCode(tempCode);
		// 3.3 设置发送短信所使用的模板中参数对应的值（在短信模板中定义的，没有可以不用设置）
		BatchSmsAttributes.SmsReceiverParams smsReceiverParams = new BatchSmsAttributes.SmsReceiverParams();
		for (Map.Entry<String, Object> entry : params.entrySet()) {
			smsReceiverParams.setParam(entry.getKey(),entry.getValue().toString());
		}
		// 3.4 增加接收短信的号码
		batchSmsAttributes.addSmsReceiver(mobile, smsReceiverParams);
		messageAttributes.setBatchSmsAttributes(batchSmsAttributes);
		logger.info("------------------初始化发送短信参数结束---------------------------------------");
		try {
			/**
			 * Step 4. 发布SMS消息
			 */
			logger.info("------------------开始发送短信，手机号为"+mobile+"---------------------------------------");
			TopicMessage ret = topic.publishMessage(msg, messageAttributes);
			logger.info(ret.getMessageId());
			logger.info(ret.getMessageBody());
			logger.info("------------------发送短信结束------------------------------------------------");
		} catch (ServiceException se) {
			se.printStackTrace();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		client.close();
		return true;
	}


	public static void main(String[] args) throws Exception {

	}


}